from flask import Blueprint, current_app, abort, jsonify, render_template

from exts import db
from models import News
from response_code import RET

bp = Blueprint("news",__name__,url_prefix="/news")


@bp.route('/<int:news_id>')
def get_news_detail(news_id):
    # 1.根据新闻编号,查询新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")

    # 2.如果新闻对象不存在直接抛出异常
    if not news:
        abort(404)
    # 2.携带数据，渲染页面

    data = {
        "news_info": news.to_dict()
    }
    try:
        news.clicks = news.clicks+1
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻点击添加失败")

    
    return render_template("news_detail.html",data=data)


# def add_clicks(news_id):
#     try:
#         news = News.query.get(news_id)
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR, errmsg="获取新闻失败")
#         # 2.如果新闻对象不存在直接抛出异常
#     if not news:
#         abort(404)
#
#         # 7. 保存到数据
#     try:
#         news.clicks = news.clicks+1
#         db.session.add(news.clicks)
#         db.session.commit()
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DBERR, errmsg="新闻点击添加失败")

    # # 2.如果新闻对象不存在直接抛出异常
    # if not news:
    #     abort(404)
    #
    # # 3.获取前6条热门新闻
    # try:
    #     click_news = News.query.order_by(News.clicks.desc()).limit(6).all()
    # except Exception as e:
    #     current_app.logger.error(e)
    #
    # # 4.将热门新闻的对象列表,转成字典列表
    # click_news_list = []
    # for item_news in click_news:
    #     click_news_list.append(item_news.to_dict())
